package cn.com.eado.crm.v.fragment


import android.os.Bundle
import android.text.Editable
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.ProgressBar
import android.widget.RadioButton
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.Navigation
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.com.eado.crm.R
import cn.com.eado.crm.app.KEY_USER_ID
import cn.com.eado.crm.app.KEY_USER_NAME
import cn.com.eado.crm.app.MyApp
import cn.com.eado.crm.app.extenstion.show
import cn.com.eado.crm.app.extenstion.toast
import cn.com.eado.crm.app.utils.SpUtil
import cn.com.eado.crm.databinding.FragmentCompanyBinding
import cn.com.eado.crm.m.bean.PostCompany
import cn.com.eado.crm.m.bean.PostCompanyUser
import cn.com.eado.crm.m.db.Company
import cn.com.eado.crm.m.db.CusUser
import cn.com.eado.crm.model.LoadStatus
import cn.com.eado.crm.model.RetryCallback
import cn.com.eado.crm.m.db.MyDatabase
import cn.com.eado.crm.v.adapter.RVCompanyAdapter
import cn.com.eado.crm.v.weiget.AutoSpinner
import cn.com.eado.crm.v.weiget.ClearEditText
import cn.com.eado.preado.app.utils.autoCleared
import cn.com.eado.crm.vm.CompanyViewModel
import com.getbase.floatingactionbutton.FloatingActionButton
import kotlinx.android.synthetic.main.fragment_company.*
import kotlin.concurrent.thread

/**
 * 企业信息管理/设计院信息管理
 */
class CompanyFragment : BaseBindingFragment<FragmentCompanyBinding>(R.layout.fragment_company) {

    private var vm by autoCleared<CompanyViewModel>()
    private var adapter by autoCleared<RVCompanyAdapter>()
    private var loadMoreState = 0
    private var hasNoMore = false
    private var total = 0
    private var mList: MutableList<Company.Row>? = null
    private var mContactList: MutableList<CusUser>? = null
    private var dialog: AlertDialog? = null

    override fun onDestroy() {
        super.onDestroy()
        activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE)
        mList = null
        mContactList = null
    }

    override fun initTheFragment() {
        initView()
        initViewModel()
        initBinding()
        loadData()
    }

    private fun initView() {
        initTitleBar()
        initOptionMenu()
        initRecyclerView()
    }

    private fun initTitleBar() {
        titleBar2.setTitle(arguments?.getString("name")?:"")
    }

    private fun initOptionMenu(){
        //add company
        fab_menu1.findViewById<FloatingActionButton>(R.id.fab_1).setOnClickListener {
            addOrEditCompany(null, null)
        }
        //add contact
        fab_menu1.findViewById<FloatingActionButton>(R.id.fab_2).setOnClickListener {
            addOrEditContact(/*null*/)
        }
        //search company
        fab_menu1.findViewById<FloatingActionButton>(R.id.fab_3).setOnClickListener {
            val bundle = Bundle()
            bundle.putString("name", arguments?.getString("name")?:"")
            Navigation.findNavController(view!!).navigate(R.id.action_companyFragment_to_companySearchFragment, bundle)
        }
    }

    private fun addOrEditCompany(pos: Int?, item: Company.Row?){
        val layout = initAddCompany(item)
        dialog = AlertDialog.Builder(activity!!)
            .setTitle(if(item == null) "新增企业" else "编辑企业")
            .setView(layout)
            .setPositiveButton("保存", null)//结合下面的dialog.getButton(必须在show()之后)，保证点击确定不关闭dialog
            .setNegativeButton("取消"){ dialog, pos -> }
            .show()
        dialog?.getButton(AlertDialog.BUTTON_POSITIVE)?.setOnClickListener{
            if (checkCompany(layout)) saveCompany(layout, pos, item)
        }
    }

    private fun initAddCompany(item: Company.Row?): View {
        val layout = View.inflate(activity, R.layout.add_company, null)
        val etName = layout.findViewById<ClearEditText>(R.id.etName)
        val etAddress = layout.findViewById<ClearEditText>(R.id.etAddress)
        val rbYes = layout.findViewById<RadioButton>(R.id.rbYes)
        val rbNo = layout.findViewById<RadioButton>(R.id.rbNo)
        val inputSpinner1 = layout.findViewById<AutoSpinner>(R.id.inputSpinner1)
        val inputSpinner2 = layout.findViewById<AutoSpinner>(R.id.inputSpinner2)
        val inputSpinner3 = layout.findViewById<AutoSpinner>(R.id.inputSpinner3)
        val inputSpinner4 = layout.findViewById<AutoSpinner>(R.id.inputSpinner4)
        val inputSpinner5 = layout.findViewById<AutoSpinner>(R.id.inputSpinner5)
        val inputSpinner6 = layout.findViewById<AutoSpinner>(R.id.inputSpinner6)
        val inputSpinner7 = layout.findViewById<AutoSpinner>(R.id.inputSpinner7)
        val inputSpinner8 = layout.findViewById<AutoSpinner>(R.id.inputSpinner8)
        //编辑
        if(item != null){
            etName.text = Editable.Factory.getInstance().newEditable(item.CompanyName)
            etAddress.text = Editable.Factory.getInstance().newEditable(item.Remark)
            if (item.IsLarge == "1") rbYes.isChecked = true
            else rbNo.isChecked = true
            inputSpinner1.setText(item.C_OwnerShip)
            inputSpinner2.setText(item.IndustryName)
            inputSpinner3.setText(item.industryType?:"")
            inputSpinner4.setText(item.C_Address)
            inputSpinner5.setText(item.city?:"")
            inputSpinner6.setText(item.GroupName)
            inputSpinner7.setText("")
            inputSpinner8.setText(item.UserName)
        }
        return layout
    }

    private fun checkCompany(layout: View): Boolean {
        val etName = layout.findViewById<ClearEditText>(R.id.etName)
        val etAddress = layout.findViewById<ClearEditText>(R.id.etAddress)
        val rbYes = layout.findViewById<RadioButton>(R.id.rbYes)
        val rbNo = layout.findViewById<RadioButton>(R.id.rbNo)
        val inputSpinner1 = layout.findViewById<AutoSpinner>(R.id.inputSpinner1)
        val inputSpinner2 = layout.findViewById<AutoSpinner>(R.id.inputSpinner2)
        val inputSpinner3 = layout.findViewById<AutoSpinner>(R.id.inputSpinner3)
        val inputSpinner4 = layout.findViewById<AutoSpinner>(R.id.inputSpinner4)
        val inputSpinner5 = layout.findViewById<AutoSpinner>(R.id.inputSpinner5)
        val inputSpinner6 = layout.findViewById<AutoSpinner>(R.id.inputSpinner6)
        val inputSpinner7 = layout.findViewById<AutoSpinner>(R.id.inputSpinner7)
        val inputSpinner8 = layout.findViewById<AutoSpinner>(R.id.inputSpinner8)
        //
        if (etName.text.trim().isEmpty()){
            activity?.toast("企业名称不能为空")
            return false
        }
        if (etAddress.text.trim().isEmpty()){
            activity?.toast("详细地址不能为空")
            return false
        }
        if (!rbYes.isChecked && !rbNo.isChecked){
            activity?.toast("请选择是否大企业")
            return false
        }
        if (inputSpinner1.isEmpty() || inputSpinner2.isEmpty() || inputSpinner3.isEmpty() ||
            inputSpinner4.isEmpty() || inputSpinner5.isEmpty() || inputSpinner6.isEmpty() ||
            inputSpinner7.isEmpty() || inputSpinner8.isEmpty()){
            return false
        }
        return true
    }

    private fun saveCompany(layout: View, pos: Int?, row: Company.Row?){
        val etName = layout.findViewById<ClearEditText>(R.id.etName)
        val etAddress = layout.findViewById<ClearEditText>(R.id.etAddress)
        val rbYes = layout.findViewById<RadioButton>(R.id.rbYes)
        val rbNo = layout.findViewById<RadioButton>(R.id.rbNo)
        val largeEnterprise = rbYes.isChecked
        val inputSpinner1 = layout.findViewById<AutoSpinner>(R.id.inputSpinner1)
        val inputSpinner2 = layout.findViewById<AutoSpinner>(R.id.inputSpinner2)
        val inputSpinner3 = layout.findViewById<AutoSpinner>(R.id.inputSpinner3)
        val inputSpinner4 = layout.findViewById<AutoSpinner>(R.id.inputSpinner4)
        val inputSpinner5 = layout.findViewById<AutoSpinner>(R.id.inputSpinner5)
        val inputSpinner6 = layout.findViewById<AutoSpinner>(R.id.inputSpinner6)
        val inputSpinner7 = layout.findViewById<AutoSpinner>(R.id.inputSpinner7)
        val inputSpinner8 = layout.findViewById<AutoSpinner>(R.id.inputSpinner8)
        val progressBar = layout.findViewById<ProgressBar>(R.id.progressBar4)
//        val userId = SpUtil.readInt(MyApp.instance, KEY_USER_ID, 0)
        //
        val postCompany = PostCompany(
            "0",
            etName.text.toString(),
            "合资",
            if(rbYes.isChecked) "1" else "0",
            "中国石油天然气集团公司（中石油）",//inputSpinner6.getText(),
            "38",
            "胡肖华",//inputSpinner7.getText(),
            "570",
            "天津市",
            "天津市,天津市",//etAddress.text.toString(),
            "工业",//inputSpinner2.getText(),
            "5"
            )
        //新增或编辑则post
        if(row == null || (row.CompanyID != postCompany.CompanyID  ||
                    row.CompanyName != postCompany.CompanyName ||
                    row.C_OwnerShip != postCompany.C_OwnerShip ||
                    row.IsLarge != postCompany.IsLarge ||
                    row.GroupName != postCompany.GroupName ||
                    row.GroupID != postCompany.GroupID ||
                    row.UserName != postCompany.UserName ||
                    row.UserID != postCompany.UserID ||
                    row.C_Address != postCompany.C_Address ||
                    row.Remark != postCompany.Remark ||
                    row.IndustryName != postCompany.IndustryName ||
                    row.IndustryID != postCompany.IndustryId
                    )){
            postData(postCompany)
            progressBar.show(activity)
        }
    }

    private fun postData(postCompany: PostCompany){
        vm.t = postCompany
        vm.setSave(true)
    }

    //--------------------------------------------------------------------------------
    private fun addOrEditContact(/*pos: Int?, item: Contact?*/){
//        if (mList?.isEmpty() == true || !mList!![position].selected){
//            activity?.toast("请选择一个企业！")
//            return
//        }
        val layout = initAddContact(/*item*/)
        dialog = AlertDialog.Builder(activity!!)
            .setTitle(/*if(item == null) */"新增联系人"/* else "编辑联系人"*/)
            .setView(layout)
            .setPositiveButton("保存", null)
            .setNegativeButton("取消"){ dialog, pos -> }
            .show()
        dialog?.getButton(AlertDialog.BUTTON_POSITIVE)?.setOnClickListener{
            if (checkContact(layout)) {
                saveContact(layout)
            }
        }
    }

    private fun initAddContact(/*contact: Contact?*/): View {
        val layout = View.inflate(activity, R.layout.add_contact, null)
        layout.findViewById<TextView>(R.id.tvName).text = "    企业："
        val inputSpinner1 = layout.findViewById<AutoSpinner>(R.id.inputSpinner1)
        val etPeople = layout.findViewById<ClearEditText>(R.id.etPeople)
        val etPosition = layout.findViewById<ClearEditText>(R.id.etPosition)
        val etPart = layout.findViewById<ClearEditText>(R.id.etPart)
        val etPhone = layout.findViewById<ClearEditText>(R.id.etPhone)
        val etCellPhone = layout.findViewById<ClearEditText>(R.id.etCellPhone)
        val etEmail = layout.findViewById<ClearEditText>(R.id.etEmail)
        val etRemark = layout.findViewById<ClearEditText>(R.id.etRemark)
        //
        if(mList?.isNotEmpty() == true){
            val list = mutableListOf<String>()
            for (row in mList!!){
                list.add(row.CompanyName)
            }
            inputSpinner1.setList(list)
        }

        return layout
    }

    private fun checkContact(layout: View): Boolean {
        val inputSpinner1 = layout.findViewById<AutoSpinner>(R.id.inputSpinner1)
        val etPeople = layout.findViewById<ClearEditText>(R.id.etPeople)
        val etPosition = layout.findViewById<ClearEditText>(R.id.etPosition)
        val etPart = layout.findViewById<ClearEditText>(R.id.etPart)
        val etPhone = layout.findViewById<ClearEditText>(R.id.etPhone)
        val etCellPhone = layout.findViewById<ClearEditText>(R.id.etCellPhone)
        val etEmail = layout.findViewById<ClearEditText>(R.id.etEmail)
        val etRemark = layout.findViewById<ClearEditText>(R.id.etRemark)
        if (inputSpinner1.getText().trim().isEmpty()){
            activity?.toast("请选择企业")
            return false
        }
        if (etPeople.text.trim().isEmpty()){
            activity?.toast("联系人不能为空")
            return false
        }
        if (etPosition.text.trim().isEmpty()){
            activity?.toast("职位不能为空")
            return false
        }
        if (etPart.text.trim().isEmpty()){
            activity?.toast("部门不能为空")
            return false
        }
        if (etPhone.text.trim().isEmpty()){
            activity?.toast("固话不能为空")
            return false
        }
        if (etCellPhone.text.trim().isEmpty()){
            activity?.toast("手机不能为空")
            return false
        }
//        if (etEmail.text.trim().isEmpty()){
//            activity?.toast("email不能为空")
//            return false
//        }
//        if (etRemark.text.trim().isEmpty()){
//            activity?.toast("备注不能为空")
//            return false
//        }
        return true
    }

    private fun saveContact(layout: View){
        val inputSpinner1 = layout.findViewById<AutoSpinner>(R.id.inputSpinner1)
        val etPeople = layout.findViewById<ClearEditText>(R.id.etPeople)
        val etPosition = layout.findViewById<ClearEditText>(R.id.etPosition)
        val etPart = layout.findViewById<ClearEditText>(R.id.etPart)
        val etPhone = layout.findViewById<ClearEditText>(R.id.etPhone)
        val etCellPhone = layout.findViewById<ClearEditText>(R.id.etCellPhone)
        val etEmail = layout.findViewById<ClearEditText>(R.id.etEmail)
        val etRemark = layout.findViewById<ClearEditText>(R.id.etRemark)
        //
        var hasCompany = false
        for(row in mList!!){
            if(inputSpinner1.getText().trim() == row.CompanyName){
                hasCompany = true
            }
        }
        if(hasCompany){
            val postCompanyUser = PostCompanyUser(
                inputSpinner1.getText(),
                "0",
                etPeople.text.toString().trim(),
                etPosition.text.toString().trim(),
                etPart.text.toString().trim(),
                etPhone.text.toString().trim(),
                etCellPhone.text.toString().trim(),
                etEmail.text.toString().trim(),
                etRemark.text.toString().trim()
            )
            postContact(postCompanyUser)
        }else{
            activity?.runOnUiThread { activity?.toast("请选择已有的企业名称") }
        }
    }

    private fun postContact(postCompanyUser: PostCompanyUser){
//        vm.t = postCompany
//        vm.setSave(true)
    }

    //////////////////////////////////////////////////////////////////////////////////////////
    private var position = 0
    private fun initRecyclerView() {
        recyclerView3.setHasFixedSize(true)
        recyclerView3.isNestedScrollingEnabled = false
        recyclerView3.layoutManager = LinearLayoutManager(activity)
        val adapter = RVCompanyAdapter({ view, pos, bean ->  //click
            //设置单选效果
                if (pos == position){
                    adapter.notifyItemChanged(position)
                    mList!![pos].selected = !mList!![pos].selected
                }else{
                    adapter.notifyItemChanged(position)
                    mList!![position].selected = false
                    position = pos
                    adapter.notifyItemChanged(position)
                    mList!![pos].selected = true
                }
            },{ pos, bean ->  //long click
                addOrEditCompany(pos, bean)
            })
        recyclerView3.adapter = adapter
        this.adapter = adapter
        //set load more listener
        recyclerView3.addOnScrollListener(object: RecyclerView.OnScrollListener(){  //监听滑动到底部加载下一页
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                val layoutManager = recyclerView.layoutManager as LinearLayoutManager
                val lastPosition = layoutManager.findLastVisibleItemPosition()
                if (lastPosition == adapter.itemCount - 1) {
                    if (mList?.size!! >= total && total > 0){
                        if (!hasNoMore) {
                            hasNoMore = true
                            activity?.toast("没有更多了")
                        }
                    }else{
                        if (loadMoreState == 0) {
                            loadMoreState = 1
                            vm.page += 1
                        }
                        if (loadMoreState == 1){
                            binding.loadingMore = true
                            vm.loadNextPage()
                        }
                    }
                }else{
                    hasNoMore = false
                }
            }
        })
    }

    private fun initViewModel(){
        vm = ViewModelProviders.of(this).get(CompanyViewModel::class.java)
        vm.company.observe(this, Observer {
            if (it.status == LoadStatus.SUCCESS){
               Log.e("tag", "data size=${it.data?.rows?.size}")
                if (it.data?.rows?.isNotEmpty() == true){
//                    horizontalScrollView1.visibility = View.VISIBLE
                    mList?.addAll(it.data.rows)
                    this.adapter.refresh(mList)
                    //about load more
                    total = it.data.total
                    binding.loadingMore?.let{
                        binding.loadingMore = false
                        if (loadMoreState == 1) vm.page += 1
                    }
                }else{
                    adapter.refresh(mList)
                }
            }else if (it.status == LoadStatus.ERROR){
                //about load more
                binding.loadingMore?.let{
                    binding.loadingMore = false
                }
            }
        })
        vm.postCompany.observe(this, Observer {
            if (it.status == LoadStatus.SUCCESS){
                Log.e("tag", "size=$it")
                if(it.data?.contains("OK") == true){
                    activity?.toast("保存成功")
                    dialog?.dismiss()
                    dialog = null
                }else{
                    activity?.toast(it.data)
                }
                activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE)
            }else if (it.status == LoadStatus.ERROR){
                activity?.toast(it.message)
                activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE)
            }
        })
    }

    private fun initBinding(){
        binding.lifecycleOwner = viewLifecycleOwner
        binding.result = vm.company
        binding.callback = object : RetryCallback {
            override fun retry() {
                vm.refresh()
            }
        }
    }

    private fun loadData(){
        if (mList == null) mList = mutableListOf()
        else mList?.clear()
        vm.userName = SpUtil.readString(MyApp.instance, KEY_USER_NAME, "known")
        vm.setLoadCompany(true)
    }



}
